<template>
  <scroll-view id="j_page" class="page" :style="{paddingBottom}">
    <div class="mgb-s">
      <floor v-if="progress.document && progress.document.user" :avatar-url="tearchInfo.avatarUrl"
        :created-at="progress.document.createdAt" role="tearch"
        :expire-at="progress.expireAt"
        :title="progress.document.name"
        :nick-name="tearchInfo.name" :blocks="progress.document.data.blocks"></floor>
    </div>

    <div class="">
      <div v-for="(n, i) in answers" :key="i">
        <div class="mgb-s">
          <floor :avatar-url="studentInfo.avatarUrl"
            :nick-name="studentInfo.name" :created-at="n.createdAt"
            role="student" :blocks="n.data.blocks" label="回复"></floor>
        </div>
        <div v-for="(nn, ii) in n.comments" :key="ii" class="mgb-s">
          <floor :avatar-url="tearchInfo.avatarUrl"
            :nick-name="tearchInfo.name" :created-at="nn.createdAt"
            role="tearch"
            :blocks="nn.data.blocks" label="点评"></floor>
        </div>
      </div>
    </div>

    <div v-if="isFormOpen" class="bg-white" style="margin-bottom: 260px;">
      <div v-if="pageRole == 'progress-owner'" class="weui-flex pdh-l pdv v-mdl" style="height: 60px;">
        <div style="width: 40px;">
          <avatar v-if="studentInfo.avatarUrl" :src="studentInfo.avatarUrl"></avatar>
        </div>
        <div class="weui-flex__item pdl-l">
          {{studentInfo.name}}
        </div>
      </div>
      <div v-if="pageRole == 'document-owner'" class="weui-flex pdh-l pdv v-mdl">
        <div style="width: 40px;">
          <avatar v-if="loginer" :src="loginer.avatarUrl"></avatar>
        </div>
        <div class="weui-flex__item pdl-s fw">
          {{loginer.nickName || ''}}
        </div>
      </div>
      <div class="pdh-l" style="min-height: 100px;">
        <textarea v-if="!isModel && pageRole == 'progress-owner'"
          maxlength="-1"
          placeholder="请输入回复内容"
          :value="textBlockValue"
          :auto-height="true"
          style="min-height: 100px;"
          placeholder-style="color: #999;"
          @input="onContentValueChange"></textarea>
        <textarea v-if="!isModel && pageRole == 'document-owner'"
          maxlength="-1"
          placeholder="请输入点评内容"
          :value="textBlockValue"
          :auto-height="true"
          style="min-height: 100px;"
          placeholder-style="color: #999;"
          @input="onContentValueChange"></textarea>
        <text v-if="isModel" class="txt">{{textBlockValue || '请输入回复内容'}}</text>
      </div>
      <div style="position: relative;" class="bd-b">
        <blocks-editor :value="uploadQueue" @change="onBlocksChange"
          @fast-reply-pick="onFastReply"
          :fastReplyPicker="pageRole == 'document-owner'"
          @upload-queue-change="onUploadQueueChange"></blocks-editor>
        <div style="position: absolute;left: 18px;bottom: 12px;" v-if="pageRole == 'document-owner'" @tap="isNeedRedo = !isNeedRedo">
          <cbx :checked="isNeedRedo">&nbsp;&nbsp;仍需修改</cbx>
        </div>
      </div>
      <div class="pd fs-5 c-gray" v-if="isNeedRedo">老师要求“仍需修改”，则该学员的作业变回“待完成”状态。</div>
    </div>
    <side-menu v-if="isShowSideMenu"></side-menu>
    <div class="fix-bottom">
      <opt-bar></opt-bar>
    </div>
    <page-common></page-common>
    <page-mask v-if="isPageLoading"></page-mask>
  </scroll-view>
</template>

<script>
import Avatar from '@/components/avatar'
import PageMask from './page-mask.vue'
import PageCommon from '@/components/page-common'
import * as $app from '@/api/app'
import * as $progress from '@/api/progress'
import { mapGetters, mapActions } from 'vuex'
import AudioPlayer from '@/components/audio-player'
import AudioRecord from '@/components/audio-record'
import Floor from '@/components/floor'
import OptBar from './opt-bar'
import base from '@/mixins/base'
import BlocksEditor from '@/components/blocks-editor'
import SideMenu from '@/components/side-menu'
import Cbx from '@/components/cbx'

export default {
  enablePullDownRefresh: true,
  mixins: [base],
  data: {
    progressId: 0,
    isPageNeedAuthUser: true,
    isNeedRedo: false,
    paddingBottom: '120px'
  },
  components: {
    PageCommon,
    AudioPlayer,
    AudioRecord,
    Avatar,
    OptBar,
    Floor,
    BlocksEditor,
    SideMenu,
    Cbx,
    PageMask
  },
  computed: {
    ...mapGetters('progress', [
      'progress',
      'isShowReplyForm',
      'pageProgressId',
      'pageRole',
      'textBlockValue',
      'openFormIds',
      'uploadQueues'
    ]),
    ...mapGetters('answer', [
      'answers'
    ]),
    ...mapGetters([
      'loginer',
      'role',
      'groupId',
      'isModel',
      'uploadingMediaNum'
    ]),
    ...mapGetters('document', [
      'document',
      'unreadCount'
    ]),
    ...mapGetters('contentBlock', [
      'contentBlock'
    ]),
    ...mapGetters('audioBlocks', [
      'audioBlocks'
    ]),
    isFormOpen () {
      return this.openFormIds.indexOf(this.progressId) >= 0
    },
    uploadQueue () {
      if (!this.progressId) return []
      if (Object.keys(this.uploadQueues).indexOf(this.progressId) < 0) return []
      return this.uploadQueues[this.progressId]
    },
    tearchInfo () {
      let info = {
        name: '',
        avatarUrl: ''
      }
      let progress = this.progress
      if (progress && progress.document && progress.document.user) {
        info = {
          name: progress.document.user.nickName || '',
          avatarUrl: progress.document.user.avatarUrl || ''
        }
      }
      return info
    },
    studentInfo () {
      let info = {
        name: '',
        avatarUrl: ''
      }
      let progress = this.progress
      if (progress && progress.member) {
        info = {
          name: progress.member.name || '',
          avatarUrl: progress.member.avatarUrl || ''
        }
      }
      return info
    }
  },
  onShareAppMessage() {
    return {
      title: this.progress.document && this.progress.document.name ? this.progress.document.name : '',
      path: '/pages/progress/main?isShowSideMenu=y&progressId=' + this.progress.id
    }
  },
  async onPullDownRefresh() {
    let {progressId} = this.getParams()
    await this.fetchById({progressId})
    wx.stopPullDownRefresh()
  },
  methods: {
    onPageShow () {
      this.isPageLoading = true
    },
    onPageHide () {
      this.isPageLoading = false
    },
    onUploadQueueChange (queue) {
      this.setUploadQueues({progressId: this.pageProgressId, uploadQueue: queue})
      let t = 0
      queue.forEach(n => {
        if (n.status === 'temp') {
          t++
        }
      })
      // 设置全局上传数
      this.setUploadingMediaNum(t)
    },
    pageScrollToBottom () {
      this.st = setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 100000
        })
      }, 200)
    },
    onRecordOk (mertail) {
      this.addItem(mertail)
      this.pageScrollToBottom()
    },
    onDelItem (idx) {
      this.delItem(idx)
    },
    ...mapActions([
      'setIsPageLoading',
      'setUploadingMediaNum',
      'setRole',
      'setEx'
    ]),
    ...mapActions('progress', [
      'fetchById',
      'updateIsShowReplyForm',
      'setPageProgressId',
      'updateTextBlocks',
      'setMediaBlocks',
      'setUploadQueues',
      'setTextBlockValue',
      'getIsCreateAble',
      'setIsNeedRedo',
      'setIsFormOpen'
    ]),
    ...mapActions('answer', [
      'setUploadQueueNum'
    ]),
    ...mapActions('contentBlock', [
      'updateContentValue'
    ]),
    ...mapActions('audioBlocks', [
      'addItem',
      'delItem'
    ]),
    onContentValueChange (e) {
      this.updateTextBlocks({progressId: this.pageProgressId, value: e.target.value})
      this.setTextBlockValue()
      this.getIsCreateAble()
    },
    onBlocksChange (blocks) {
      this.setMediaBlocks({progressId: this.pageProgressId, blocks})
      this.getIsCreateAble()
    },
    async loginBack (loginer) {
      try {
        this.isPageLoading = true
        if (!this.role) {
          this.setRole('student')
        }
        let {progressId} = this.getParams()
        if (!progressId) {
          this.isPageLoading = false
          return
        }
        this.progressId = progressId
        this.setPageProgressId(progressId)
        await this.fetchById({progressId})
        await this.read(progressId)
        this.setIsPageLoading(false)
        // this.pageScrollToBottom()
        if (!this.progress.id) {
          wx.showModel({title: '资源缺失！'})
          this.isPageLoading = false
          return
        }

        // 老师批改作业时把身份切换成老师
        if (this.pageRole === 'document-owner') {
          this.setRole('teacher')
        }
        let pageTitle = '作业'
        if (this.pageRole === 'progress-owner') {
          if (this.progress.document && this.progress.document.user && this.progress.document.user.nickName) {
            pageTitle = this.progress.document.user.nickName
          }
        } else {
          if (this.progress.member && this.progress.member.name) {
            pageTitle = this.progress.member.name
          } else if (this.progress.user && this.progress.user.nickName) {
            pageTitle = this.progress.user.nickName
          }
        }
        wx.setNavigationBarTitle({
          title: pageTitle
        })
        this.isPageLoading = false
      } catch (e) {
        this.$debug({err: e})
      }
    },
    onFastReply (words) {
      this.updateTextBlocks({progressId: this.pageProgressId, value: this.textBlockValue + words})
      this.getIsCreateAble()
    },
    async read (progressId) {
      let _progress = await $progress.read(progressId)
      this.$store.commit('task/TASK_RESET_TASKS_UNREAD_COUNT', {
        taskId: _progress.task.id
      })
      this.$store.commit('progress/PROGRESS_RESET_PROGRESSES_UNREAD_COUNT', progressId)
      this.$store.commit('document/DOCUMENT_SET_UNREAD_COUNT', this.unreadCount - 1 <= 0 ? 0 : this.unreadCount - 1)
    }
  },
  onUnload () {
    if (this.st) clearTimeout(this.st)
    this.setEx('__')
  },
  onHide () {
    if (this.st) clearTimeout(this.st)
    this.setEx('__')
  },
  watch: {
    isNeedRedo (nv) {
      this.setIsNeedRedo(nv)
    },
    progressId () {
      this.setTextBlockValue()
      this.getIsCreateAble()
    },
    uploadingMediaNum () {
      this.getIsCreateAble()
    },
    role () {
      this.updateIsShowReplyForm(false)
    },
    isFormOpen (nv) {
      if (!nv) return
      this.pageScrollToBottom()
    },
  }
}
</script>

<style scoped lang="less">
textarea, text.txt {
  margin: 0;
  display: block;
  padding: 0;
  border: none;
  padding-bottom: 20px;
  font-size: 16px;
  line-height: 1.2;
}
text.txt {
  padding-top: 8px;
  padding-left: 5px;
}
</style>
